package pers.cz.node;

import org.openqa.selenium.remote.RemoteWebDriver;
import pers.cz.mxgraph.MxCell;
import pers.cz.selenium.component.AlertBoxComponent;
import pers.cz.selenium.component.ButtonComponent;
import pers.cz.selenium.component.ContextComponent;

/**
 * @program: PostGirl-panent
 * @description: 弹框处理
 * @author: Cheng Zhi
 * @create: 2023-01-23 14:31
 **/
public class AlertHandleNode extends AbstractNode {

    public AlertHandleNode(MxCell mxCell) {
        super(mxCell);
    }

    @Override
    public void runNode(NodeCallBack callBack) throws Exception{
        RemoteWebDriver driver = getDriver();
        // 处理弹框,根据弹框类型来处理 1: 系统弹框 2：普通弹框（按照按钮处理）
        if ("1".equals(mxCell.getMxObjectData().get("operation"))) {
            ContextComponent contextComponent = new ContextComponent(driver);
            boolean haveAlert = contextComponent.isHaveAlert();
            if (haveAlert) {
                contextComponent.closeAlert();
            }
        } else if ("2".equals(mxCell.getMxObjectData().get("operation"))) {
            String fulllPath = mxCell.getMxObjectData().get("fullPath");
            dealAlert(mxCell, fulllPath, driver);
        }

    }

    private void dealAlert(MxCell mxCells, String fulllPath, RemoteWebDriver driver) {
        String ext = mxCells.getMxObjectData().get("ext");

        if (ext != null && "1".equals(ext)) {
            try {
                boolean flag = false;
                String[] splits = fulllPath.split(";");
                for (String split : splits) {
                    if (buttonClick(split, driver)) {
                        flag = true;
                        break;
                    }
                }
            } catch (Exception e) {
                // 点击失败
            }
        } else if (ext != null && "2".equals(ext)) {
            boolean flag = false;
            String[] splits = fulllPath.split(";");
            for (String split : splits) {
                if (buttonClick(split, driver)) {
                    flag = true;
                    break;
                }
            }

            if (!flag) {
                throw new RuntimeException("弹框处理失败");
            }
        }
    }

    private boolean buttonClick(String fulllPath, RemoteWebDriver driver) {

        boolean flag = false;
        try {
            ButtonComponent buttonComponent = new ButtonComponent(fulllPath, driver);
            buttonComponent.click();
            flag = true;
        } catch (Exception e) {
            flag = false;
        }

        return flag;
    }
    @Override
    public void verify() {

    }

    @Override
    public String getName() {
        return mxCell.getName();
    }
}
